<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue';
  import { useRoute, useRouter } from "vue-router";
  import {client} from '@/utils/alioss'
  import axios from '@/utils/axios';
  import { showToast } from "vant";
  import WangEditor from 'wangeditor'

  const route = useRoute();
  const router = useRouter();
  const activeTab = ref('mainText');
  let instance;
  const editor = ref(null)

  // 同步路由和标签状态
  watch(
      () => route.fullPath,
      (path) => {
        if (path.includes('comment')) {
          activeTab.value = 'comment';
        } else {
          activeTab.value = 'mainText';
        }
      },
      { immediate: true }
  );

  const tabs = ref([
    { name: 'mainText', title: '正文', path: '/postDetails/:postId/mainText' },
    { name: 'comment', title: '评论', path: '/postDetails/:postId/comment' },
  ]);

  const data = reactive({
    token: '',
    showAdd: false,
    isLiked: false,//点赞
    isCollected: false,//收藏
    addForm:{
      postId:0,//帖子id
      content: '',//内容
    },
    post: {
      postId: 0,
      title: "",
      content: "",
      likeCount: 0,
      commentCount: 0,
      collectCount: 0,
      isLiked: false,
      isCollected: false,
      publishTime: "",
      user: {},
      games: { gameName: '' },
      postImages: [{ imageUrl: '' }],
      postTags: [],
      comments: [],
    }
  });

  const loadDialog = ()=>{
    initEditor();
  }
  const destroyEditor = () =>{
    instance.destroy()
    instance = null
  }
  const initEditor = () => {
    instance = new WangEditor(editor.value)
    instance.config.showLinkImg = false
    instance.config.showLinkImgAlt = false
    instance.config.showLinkImgHref = false
    instance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
    instance.config.uploadFileName = 'file'
    instance.config.uploadImgHeaders = {
      token: "234"
    }
    instance.config.uploadImgHooks = {
      customInsert: function (insertImgFn, result) {
        if (result.data && result.data.length) {
          result.data.forEach(item => insertImgFn(item))
        }
      }
    }

    instance.config.uploadImgServer = "";

    instance.config.customUploadImg = function (resultFiles, insertImgFn) {

      resultFiles.forEach(file => {
        var fileName = 'abc/'+'banner' + `${Date.parse(new Date())}` + file.name;
        client().put(fileName, file).
        then((res)=>{
          insertImgFn(res.url);
        })

      });
    };


    Object.assign(instance.config, {
      onchange() {
        console.log('change')
      },
    })
    instance.create();
  }

  // 切换标签
  const onTabClick = (tab) => {
    const tabConfig = tabs.value.find(t => t.name === tab.name);
    if (!tabConfig) return;

    const postId = route.params.postId;
    const targetPath = tabConfig.path.replace(':postId', postId);
    router.replace(targetPath);
  };

  // 初始化帖子数据
  const init = () => {
    const postId = route.params.postId;
    const url = "/api/hotStop/getByPostId/" + postId;
    axios.post(url)
        .then(res => {
          data.post = res.data;
        })
        .catch(err => {
          console.error("获取帖子详情失败:", err);
          showToast("加载失败，请重试");
        });
  };

  // 交互操作
  const toggleLike = () => {
    data.post.isLiked = !data.post.isLiked;
    data.post.likeCount += data.post.isLiked ? 1 : -1;
    // 实际项目中这里需要调用接口
  };

  const toggleCollect = () => {
    data.post.isCollected = !data.post.isCollected;
    data.post.collectCount += data.post.isCollected ? 1 : -1;
    // 实际项目中这里需要调用接口
  };

  onMounted(() => {
    init();
  });

  // 返回上一页
  const onClickLeft = () => {
    router.go(-1);
  };

  const onClickRight = () => showToast('分享功能开发中');

  const doAdd = () => {
    // 确保获取到编辑器的最新内容
    if (instance) {
      console.log("编辑器内容：", instance.txt.html());
      data.addForm.content = instance.txt.html();
      data.addForm.postId = data.post.postId;
    }

    const url = "/api/hotStop/commentsadd";
    axios.post(url, data.addForm)
        .then(res => {
          console.log("data.addForm",data.addForm);
          data.showAdd = false;
          onMounted();
        })
  };
</script>

<template>
  <div class="post-detail-container">
    <!-- 导航栏 -->
    <van-nav-bar
        title=""
        left-text=""
        right-text="分享"
        left-arrow
        fixed
        placeholder
        class="custom-nav-bar"
        @click-left="onClickLeft"
        @click-right="onClickRight"
    >
      <template #title>
        <van-tabs
            v-model:active="activeTab"
            @click-tab="onTabClick"
            swipeable
            class="tab-container"
        >
          <van-tab v-for="tab in tabs" :key="tab.name" :title="tab.title" :name="tab.name" />
        </van-tabs>
      </template>
    </van-nav-bar>

    <!-- 内容区域 -->
    <div class="content-container">
      <router-view/>
    </div>

    <!-- 底部操作栏 -->
    <div class="footer-actions">
      <el-input
          placeholder="写下你的评论..."
          class="comment-input"
          clearable
          @click="data.showAdd = !data.showAdd"
      ></el-input>

      <div class="post-stats">
        <div
            class="stat-item"
            :class="{ active: data.post.isLiked }"
            @click.stop="toggleLike"
        >
          <van-icon name="like-o" class="stat-icon" :color="data.post.isLiked ? '#FF4D4F' : ''" />
          <span class="stat-text">{{ data.post.likeCount }}</span>
        </div>
        <div
            class="stat-item"
            :class="{ active: data.post.isCollected }"
            @click.stop="toggleCollect"
        >
          <van-icon name="star-o" class="stat-icon" :color="data.post.isCollected ? '#FAAD14' : ''" />
          <span class="stat-text">{{ data.post.collectCount }}</span>
        </div>
        <div class="stat-item" @click.stop="onClickRight">
          <van-icon name="share" class="stat-icon" />
          <span class="stat-text">分享</span>
        </div>
      </div>
    </div>
  </div>

  <el-dialog @open="loadDialog" @closed="destroyEditor" :close-on-click-modal="false" v-model="data.showAdd" style="width: 100%;height: 70%;">
    <el-form label-width="120">
      <el-form-item>
        <div ref="editor" ></div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doAdd">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<style scoped>
  .custom-nav-bar {
    --van-nav-bar-height: 56px;
    background-color: #fff;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }

  .tab-container :deep(.van-tabs__content) {
    display: none;
  }

  .custom-nav-bar :deep(.van-tab) {
    padding: 0 16px;
    font-size: 16px;
    font-weight: 500;
  }

  .custom-nav-bar :deep(.van-tab--active) {
    color: #1890FF;
  }

  .custom-nav-bar :deep(.van-tabs__line) {
    background-color: #1890FF;
    height: 3px;
    width: 24px !important;
  }

  .content-container {
    padding-top: 0px;
    padding-bottom: 65px;
    min-height: 100vh;
    box-sizing: border-box;
    background-color: #f5f5f5;
  }

  .footer-actions {
    display: flex;
    align-items: center;
    padding: 8px 15px;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: white;
    border-top: 1px solid #eee;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.03);
    z-index: 999;
    box-sizing: border-box;
  }

  .comment-input {
    flex: 1;
    --el-input-height: 40px;
    border-radius: 20px;
    background-color: #f5f5f5;
    border: none;
    padding-left: 16px;
  }

  /* 新增的按钮样式，与post-stats保持一致 */
  .post-stats {
    display: flex;
    margin-left: 12px;
  }

  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #666;
    font-size: 12px;
    cursor: pointer;
    transition: color 0.2s;
    padding: 5px 10px;
  }

  .stat-item:hover {
    color: #1989fa;
  }

  .stat-icon {
    font-size: 20px;
    margin-bottom: 5px;
  }

  .stat-text {
    font-size: 13px;
  }

  .stat-item.active {
    color: #FF4D4F;
  }
</style>
